#ifndef GAME_ANIMATION_GEOMETRY_MESH2GEOMETRY_H
#define GAME_ANIMATION_GEOMETRY_MESH2GEOMETRY_H
//
// Game Animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <animation/configuration.h>

#include <OpenTissue/core/containers/mesh/trimesh/util/trimesh_valency.h>

namespace animation
{

  /**
   * Conversion of OpenTissue Mesh to internal geometry representation.
   *
   * @param mesh      An OpenTissue mesh type.
   * @param geometry  Upon return this argument contains the converted mesh.
   */
  template<typename mesh_type,typename geometry_type>
    void mesh2geometry(mesh_type const & mesh,geometry_type & geometry)
  {
    typedef typename mesh_type::const_vertex_iterator          vertex_iterator;
    typedef typename mesh_type::const_face_iterator            face_iterator;
    typedef typename mesh_type::const_face_vertex_circulator   face_vertex_circulator;
    typedef typename geometry_type::vertex_type                vertex_type;

    unsigned int cnt_vertices = mesh.size_vertices();
    unsigned int cnt_indices  = 0;

    face_iterator f_begin = mesh.face_begin();
    face_iterator f_end   = mesh.face_end();
    face_iterator f = f_begin;
    for(;f!=f_end;++f)
      cnt_indices += OpenTissue::trimesh::valency(*f);        //--- Ideally this could be anything, however geometry_type
                                         //--- only supports triangles!!! To save time one could thus
                                         //--- use:
                                         //---
                                         //---  cnt_indices = 3*mesh.size_faces();

    geometry = geometry_type(cnt_vertices,cnt_indices);
    unsigned int j = 0;
    for(f = f_begin;f!=f_end;++f)
    {
      face_vertex_circulator v(*f),v_end;
      for(;v!=v_end;++v,++j)
      {
        geometry.get_index(j) = v->get_handle().get_idx();
      }
    }
    //--- We expect that default mesh traits have been used.
    vertex_iterator v     = mesh.vertex_begin();
    vertex_iterator v_end = mesh.vertex_end();
    for(unsigned int i=0;v!=v_end;++v,++i)
    {
      vertex_type & g = geometry.get_vertex(i);
      g.m_coord[0]  = v->m_coord(0);
      g.m_coord[1]  = v->m_coord(1);
      g.m_coord[2]  = v->m_coord(2);      
      g.m_normal[0] = v->m_normal(0);
      g.m_normal[1] = v->m_normal(1);
      g.m_normal[2] = v->m_normal(2);
      g.m_color[0]  = v->m_color(0);
      g.m_color[1]  = v->m_color(1);
      g.m_color[2]  = v->m_color(2);
      g.m_tex0[0]   = v->m_u;
      g.m_tex0[1]   = v->m_v;
    }
  };

} // namespace animation

// GAME_ANIMATION_GEOMETRY_MESH2GEOMETRY_H
#endif
